package cc.bookcloud.tool.ocr.common.excel;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @Desc:
 * @version:
 * @author: oycq
 * @date: 2022/05/24 19:04
 **/
@Component
public class DeleteFileListener implements ApplicationListener<DeleteFileEvent> {


    @Override
    public void onApplicationEvent(DeleteFileEvent event) {
        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            String filePath = path + "static/DBFile/";
            File[] files = new File(filePath).listFiles();
            if(files ==null){
                return;
            }
            for (File file : files) {
                if (file.isFile()) {
                    //删除当前时间一分钟前的所有文件
                    String time = file.getName().split("\\.")[0];
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime fileTime = Instant.ofEpochMilli(Long.parseLong(time)).atZone(zoneId).toLocalDateTime();
                    LocalDateTime now = LocalDateTime.now().minusMinutes(1);
                    if (fileTime.isBefore(now)) {
                        file.delete();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
